/**
 * 申请单所用的城市-可以选择多城市
 * @author hongwei 2018-09-07
 */
(function (window) {
    'use strict';
    var applyCity = function(params) {
        $.extend(this.params, params);
        this._init();   //初始化操作
    };
    applyCity.prototype = {
        params: {
            cityType        : 'single' //城市类型,single是单城市,multiply是多城市(必填)
            ,firstStorage   : ''       //apply: travel_site,hotel:(必填)
            ,secondStorage  : ''       //apply : travel_destination,hotel:(必填)
            ,jsonFilePath   : ''       //json路径,apply:../train/train_city_list.json
            ,all_city_list  : []       //所有城市列表
        }

        ,_init :function () {
            var that = this;

            //that.removeStorage();           //step1:初始删除storage
            that.getCityByJson();           //step2:通过JSON获取城市
            //that.getCityByRemote();       //step3:通过远程获取城市，不用了
            that.searchBtn();               //step5:搜索城市，执行step9
            that.getAllCityList();          //step9:城市列表筛选
            if (that.params.cityType === 'single') {
                that.hotCityClick();        //step4:点击热门城市
                that.hasSelectedSingle();   //step6:单城市列表中城市点击操作
                that.searchInputCity(that.params.firstStorage); //step8:输入框输入城市定击确定
            }
            if (that.params.cityType === 'multiply') {
                that.hotCityMultiClick();    //step5:多城市点击填加城市
                that.hasSelectedMulti();     //step7:多城市列表中城市点击操作
                that.searchInputCity(that.params.secondStorage); //step8:输入框输入城市定击确定
            }
            //that.validateSelect();        //工具1:验证选择
            //that.allCities();             //工具2:所有城市存储到storage
        }

        //step1:初始删除storage
        ,removeStorage: function () {
            var that = this;
            $api.rmStorage('all_cities'); //去掉所有城市的storage
            $api.rmStorage(that.params.firstStorage);
            $api.rmStorage(that.params.secondStorage);
        }

        //step2:通过JSON获取城市
        ,getCityByJson : function() {
            var that = this;
            var city_list = [];
            $.getJSON(that.params.jsonFilePath, function(ret){
                if (ret.code === 1) {
                    //step1:获取数据
                    var dataInter = ret.data;
                    city_list = dataInter;
                    $.extend(that.params.all_city_list, city_list);   //整合参数
                    //step2:模板赋值
                    var interText = doT.template($("#addressListScript").text());
                    $("#addressList").append(interText(dataInter));
                    //step3:排序
                    sort();
                    //step4:获取所有城市
                    that.allCities();
                } else {
                    alert(ret.msg);
                }
            });
        }

        //step3:通过远程获取城市，不用了
        ,getCityByRemote : function () {
            var city_list = [];
            var param={};
            param.url = Config.train.trainCityList;
            param.data = {};
            ajax(param,function(data){
                if (data.code === 1) {
                    var dataInter = data.data.data;
                    city_list = dataInter;
                    var interText = doT.template($("#addressListScript").text());
                    $("#addressList").append(interText(dataInter));
                    sort();
                } else {
                    alert(data.msg);
                }
            })
        }

        //step4:点击热门城市
        ,hotCityClick: function (){
            var that = this;
            $('.hot_city').click(function () {
                var  city_name = $(this).text();
                $('.search_city').val(' ');
                $('.search_city').val(city_name);
                $api.setStorage(that.params.firstStorage, city_name);
            });
        }

        //step5:多城市点击填加城市
        ,hotCityMultiClick: function () {
            var that = this;
            $('.hot_city').click(function () {
                var city_name_list = $(this).text();  //单击获取的城市
                var city_name_search = $(".search_city").val(); //搜索框中城市
                if(city_name_search === ''){
                    $('.search_city').val(city_name_list);
                    $api.setStorage(that.params.secondStorage, city_name_list);
                }else{
                    if(!that.validateSelect(city_name_list)){
                        return false;
                    }
                    $('.search_city').val(city_name_search + ' ' + city_name_list);
                    $api.setStorage(that.params.secondStorage, city_name_search + ' ' + city_name_list);
                }
            });
        }

        //step5:搜索城市，执行step9
        ,searchBtn : function (){
            var that = this;
            $('#search').click(function () {
                that.getAllCityList($(this).value);
            });
        }

        //step6:单城市列表中城市点击操作
        ,hasSelectedSingle :function (){
            var that = this;
            $('body').on('click', '.sort_list', function () {
                var cityName = $(this).find('div').text();
                //留空及赋值
                $('.search_city').empty().val(cityName);
                //加对号
                $(this).siblings().children(".aui-icon-correct").addClass("hidden").removeClass("selected");
                $(this).find(".aui-icon-correct").removeClass("hidden").addClass("selected");
                //存储变量
                $api.setStorage(that.params.firstStorage, cityName);
            })
        }

        //step7:多城市列表中城市点击操作
        ,hasSelectedMulti :function (){
            var that = this;
            $('body').on('click', '.sort_list', function () {
                var cityName = $(this).find('div').text();
                var city_name = $(".search_city").val();
                if(city_name === ''){
                    $('.search_city').val(cityName);
                    $api.setStorage(that.params.secondStorage, cityName);
                }else{
                    if(!that.validateSelect(cityName)){
                        return false;
                    }
                    $('.search_city').val(city_name + ' ' + cityName);
                    $api.setStorage(that.params.secondStorage, city_name + ' ' + cityName);
                }
            })
        }


        //step8:输入框输入城市定击确定
        ,searchInputCity : function (inputCityStorageName) {
            $('#inputCity').on('input', function () {
                var cityName = $(this).val();
                $api.setStorage(inputCityStorageName, cityName);
            });
        }

        //step9:城市列表筛选
        ,getAllCityList : function(search){
            var that = this;

            $('#addressList').text('');
            var new_list = [];
            if (search === '') {
                $.each(that.params.all_city_list, function (value, index) {
                    if (parseInt(value.name.indexOf(search)) !== -1) {
                        new_list.push(value);
                    }
                });
            } else {
                new_list = that.params.all_city_list;
            }
            $api.setStorage(that.params.firstStorage, search);
            var interText = doT.template($("#addressListScript").text());
            $("#addressList").append(interText(new_list));
            sort();
        }

        //工具1:验证选择
        ,validateSelect : function (cityName) {
            var city_name = $(".search_city").val().trim().replace(/\s+/g, ' ');
            var city_arr = city_name.split(" ");
            //城市最多5个
            if(city_arr.length > 4){
                alert('城市最多5个');
                return false;
            }
            //判断是否选择
            if(city_arr.indexOf(cityName) > -1){
                alert(cityName+" 已经选择");
                return false;
            }
            return true;
        }

        //工具2：所有城市存储到storage
        , allCities : function () {
            var that = this;

            //所有城市
            var allCityArray = that.params.all_city_list; //所有城市
            var allCityString = [] ;
            for(var i=0; i < allCityArray.length; i++){
                allCityString.push(allCityArray[i]["name"]);
            }
            $api.setStorage('all_cities', allCityString);
        }
    };
    window.applyCity =  applyCity;
})(window);